import React, { useState, useEffect } from 'react';
import { Button, Table, Input, Space, Select, Modal, Form, message, DatePicker } from 'antd';
import { addOrder, getProduct, getCompany } from '@/api/services';
import { v4 as uuidv4 } from 'uuid'; // 导入 uuid 库
import moment from 'moment';


interface childrenProps {
    onCancel: () => void;
    getOrderList: () => void;
}

interface ProductDetail {
    key: string; // 新增一个 key 属性作为唯一标识符
    product: string;
    quantity: number;
}

const InfoModal: React.FC<childrenProps> = ({ onCancel, getOrderList }) => {
    const [productList, setProductList] = useState<any>([]);//产品列表
    const [modalOpen, setModalOpen] = useState<boolean>(false);
    const [form] = Form.useForm();
    const [productDetails, setProductDetails] = useState<any>([]);
    const user = JSON.parse(localStorage.getItem('user') as any);
    const [company, setCompany] = useState<any>([]);

    useEffect(() => {
        // 初始化时添加两个空的产品明细行
        setProductDetails([{ key: uuidv4(), product: '', quantity: 0 }]);
    }, []);

    //获取仓库产品
    useEffect(() => {
        getProduct().then((res: any) => {
            console.log(res);
            const options = res.results.map((goods: any) => ({
                value: goods.goods_name,
                label: goods.goods_name,
            }));
            setProductList(options);
        })
    }, [])

    //获取合作公司
    useEffect(() => {
        getCompany().then((res: any) => {
            console.log(res);
            const options = res.results.map((goods: any) => ({
                value: goods.customer_company,
                label: goods.customer_company,
            }));
            setCompany(options);
        })
    }, [])

    //新增订单
    const addOrderList = async () => {
        const validate = await form.validateFields();
        const orderDetail = Object.values(productDetails).map((item: any) => `${item.product}||${item.quantity}`).join('||');
        const currentTime = moment().format('YYYY-MM-DD HH:mm:ss');
        addOrder({
            userId: user.user_id,
            money: Number(validate.order_money),
            detail: orderDetail,
            posttime: currentTime,
            deadline: moment(validate.order_deadline).format('YYYY-MM-DD HH:mm:ss'),
            customerCompany: validate.customerCompany
        }).then((res: any) => {
            console.log(res);
            message.success('新增成功');
            setModalOpen(false);
            getOrderList();
            onCancel();
        })
    }

    const handleAddProduct = () => {
        const newProductDetail: ProductDetail = {
            key: uuidv4(), // 使用 uuid 生成唯一标识符
            product: '',
            quantity: 0,
        };
        setProductDetails([...productDetails, newProductDetail]);
    };

    const handleProductChange = (key: number, value: string) => {
        const updatedProductDetails = productDetails.map((detail: { key: number; }) => {
            if (detail.key === key) {
                return { ...detail, product: value };
            }
            return detail;
        });
        setProductDetails(updatedProductDetails);
        console.log(updatedProductDetails)

    };

    const handleQuantityChange = (key: number, value: any) => {
        const updatedProductDetails = productDetails.map((detail: { key: number; }) => {
            if (detail.key === key) {
                return { ...detail, quantity: value };
            }
            return detail;
        });
        setProductDetails(updatedProductDetails);

    };

    const detailColumns: any = [
        {
            title: '产品',
            dataIndex: 'product',
            render: (_: any, record: any) => (
                <Select
                    style={{ width: 120 }}
                    onChange={(value) => handleProductChange(record.key, value)}
                    options={productList}
                />
            )
        },
        {
            title: '数量',
            dataIndex: 'quantity',
            render: (_: any, record: any) => (
                <Input value={record.nums} onChange={(e) => handleQuantityChange(record.key, e.target.value)} />
            )
        }
    ]
    //新增订单footer
    const ModalFooter = (
        <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <Button
                type="primary"
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={addOrderList}
            >
                确定
            </Button>
            <Button
                style={{ marginRight: 16, borderRadius: 6 }}
                onClick={onCancel}
            >
                取消
            </Button>
        </div>
    )
    return (
        <Modal
            open={true}
            title="新增订单"
            onCancel={onCancel}
            footer={ModalFooter}
        >
            <Form
                form={form}
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 14 }}
            >
                <Form.Item label="合作公司" name="customerCompany">
                    <Select
                        style={{ width: 270 }}
                        options={company}
                    />
                </Form.Item>
                <Form.Item label="订单金额" name="order_money">
                    <Input />
                </Form.Item>
                <Form.Item label="订单明细">
                    <Table
                        columns={detailColumns}
                        dataSource={productDetails}
                        pagination={false}
                        bordered
                    />
                    <Button type="dashed" onClick={handleAddProduct} style={{ marginTop: '20px' }}>
                        新增产品
                    </Button>
                </Form.Item>
                <Form.Item label="订单截止时间" name="order_deadline">
                    <DatePicker
                        showTime
                        onChange={(value, dateString) => {
                            console.log('Selected Time: ', value);
                            console.log('Formatted Selected Time: ', dateString);
                        }}
                    />
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default InfoModal;